package server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import servlet.MyRequest;
import servlet.MyServlet;
import servlet.ServletMappingTree;

public class MyClassLoader extends ClassLoader{

	private String path="";
	//自定义类加载器，采用模板模式
	public Class<?> findClass(String name){
		System.out.println(name);
		String packages = name.replace(".", "\\");
		byte[] data = loadClassData(packages);
        return defineClass(name, data, 0, data.length);
    }
	private byte[] loadClassData(String name){
		 FileInputStream fis = null;
	        byte[] data = null;
	        try {
	             fis = new FileInputStream(new File(path+name+".class"));
	 			System.out.println(path+name+".class");
	             ByteArrayOutputStream baos = new ByteArrayOutputStream();
	            int ch = 0;
	            while ((ch = fis.read()) != -1) {
	                 baos.write(ch);
	             }
	             data = baos.toByteArray();
	         } catch (IOException e) {
	             e.printStackTrace();
	         }
	        return data;
	}

	@SuppressWarnings("unchecked")
	//加载Servlet的class文件
	public Class<MyServlet> loadServlet(MyRequest request) {
		path = WebServer.getServerContext().getServerRootPath()+"/webapps/";
		if(!request.getProjectName().equals("")){
			path += request.getProjectName()+"/";
		}
		path += "WEB-INF/classes/";
		ServletMappingTree smt = WebServer.getServerContext().getServletMappingTree();
		System.out.println(request.getRequestResourcePath());
		String QName = smt.search(request.getRequestResourcePath());
		if(QName==null){
			return null;
		}
		else{
			try {
				Class<MyServlet> servletClass = (Class<MyServlet>)this.loadClass(QName);
				return servletClass;
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
	}
	//加载JSP编译完的Servlet的class文件
	public Class<MyServlet> loadJspServlet(MyRequest request){
		path = WebServer.getServerContext().getServerRootPath()+"/work/MyServer/";
		if(!request.getProjectName().equals("")){
			path += request.getProjectName()+"/";
		}
		path += "pku/ss/jsp/";
		String QName = (request.getRequestResourcePath().substring(request.getRequestResourcePath().indexOf("/", 1)+1, request.getRequestResourcePath().lastIndexOf("."))+"_jsp").replace("/", ".");
		if(QName==null){
			return null;
		}
		else{
			try {
				Class<MyServlet> servletClass = (Class<MyServlet>)this.loadClass(QName);
				return servletClass;
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
	}


}
